import threading
import time
import socket


def tcp_link(_sock, _address):
    print('Accept new connection from %s:%s...' % _address)
    while True:
        data = _sock.recv(1024)
        time.sleep(0.5)
        if not data or data.decode('utf-8') == 'exit':
            break
        print('Received:', data.decode('utf-8'))
        _sock.send(('Hello, %s!' % data.decode('utf-8')).encode('utf-8'))
    _sock.close()
    print('Connection from %s:%s closed.' % _address)


s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('172.23.76.64', 8009))
s.listen(5)
print('Waiting for connection...')

while True:
    # 接受一个新连接:
    sock, address = s.accept()
    # 创建新线程来处理TCP连接:
    t = threading.Thread(target=tcp_link, args=(sock, address))
    t.start()
